package org.iteam.commons.utils;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

/**
 * 图片文件缩放并填充工具类
 * 
 * @author arts
 * 
 */
public class ImageUtils {

	public static byte[] changeImages(int width, int height, File srcFile)
			throws IOException {
		String fileName = srcFile.getName();
		String filetype = fileName.substring(fileName.indexOf(".") + 1,
				fileName.length());
		Image src = javax.imageio.ImageIO.read(srcFile); // 构造Image对象
		int w = src.getWidth(null); // 得到图宽
		int h = src.getHeight(null); // 得到图长
		// 得到缩放倍数
		double size = 1;
		if (width >= height) {
			size = height * 1.0 / h;
		}
		if (width <= height) {
			size = width * 1.0 / w;
		}
		w = (int) (w * size);
		h = (int) (h * size);

		while (w > width || h > height) {
			size = 1;
			if (w > h) {
				size = width * 1.0 / w;
			}
			if (w < h) {
				size = height * 1.0 / h;
			}
			w = (int) (w * size);
			h = (int) (h * size);
		}
		// 填充空白 止值
		int s_w = 0;
		int s_h = 0;
		s_h = (int) ((height - h) / 2);
		s_w = (int) ((width - w) / 2);
		if (s_h < 0) {
			s_h = s_h * -1;
		}
		if (s_w < 0) {
			s_w = s_w * -1;
		}
		Image new_img = src.getScaledInstance(w, h, Image.SCALE_SMOOTH);
		// 图片放缩
		BufferedImage tag = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);
		Graphics g = tag.getGraphics();
		g.setColor(Color.WHITE);
		g.fillRect(0, 0, width, height);
		g.drawImage(new_img, s_w, s_h, w, h, null); // 绘制缩小后的图
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		ImageIO.write(tag, filetype, out);
		byte[] b = out.toByteArray();
		return b;
		// 写入图片
		// ImageIO.write(tag, filetype, new File(savePath));
		// return ImageBase64Utils.getBytes(savePath);
	}

}
